//
//  SpecificationTableViewCell.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/17.
//

import UIKit

class SpecificationTableViewCell: UITableViewCell {
    
    var titleBtn: UIButton!
    var collectionView: UICollectionView!
    var dataArray: [EntitiesModel] = []
    var contentModel: CarDetailsContentModel!
    var seaCarFlag: Bool = false
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?){
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = .white
        self.clipsToBounds = true
        self.selectionStyle = .none
        
        self.addInitSubview()
        self.initCollectionView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func addInitSubview() {
        titleBtn = UIButton.init(frame: CGRect.zero)
        titleBtn.setTitle(MMLocalizedString("specifications", comment: "汽车规格"), for: .normal)
        titleBtn.setTitle(MMLocalizedString("specifications", comment: "汽车规格"), for: .highlighted)
        titleBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        titleBtn.setTitleColor(Theme.titleLabColor, for: .normal)
        titleBtn.setTitleColor(Theme.titleLabColor, for: .highlighted)
        titleBtn.contentHorizontalAlignment = .left
        self.contentView.addSubview(titleBtn)
    }
    
    func initCollectionView() {
        let layout =  UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        self.collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 35),collectionViewLayout: layout)
        self.collectionView.dataSource = self
        self.collectionView.delegate = self
        self.collectionView.backgroundColor = .clear
        self.collectionView.register(SpecificationCell.self, forCellWithReuseIdentifier: "SpecificationCell")
        self.collectionView.isScrollEnabled = false
        self.collectionView.isUserInteractionEnabled = false
        self.contentView.addSubview(self.collectionView)
        
        self.addLayout()
    }
    
    func addLayout() {
        self.titleBtn.snp.makeConstraints{ make in
            make.top.equalTo(20)
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.height.equalTo(20)
        }
        
        self.collectionView.snp.makeConstraints { make in
            make.top.equalTo(self.titleBtn.snp.bottom).offset(10)
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.height.greaterThanOrEqualTo(40)
            make.bottom.equalTo(-10).priority(.high)
        }
    }
    
    /// model
    func setContentModel(contentModel: CarDetailsContentModel? = nil){
        self.contentModel = contentModel
        self.dataArray = []
        self.dataArray = contentModel?.otherParameterJsonNew ?? []
      
        //燃油种类
        let engineModel = EntitiesModel.init()
        engineModel.paramName = MMLocalizedString("fuel_type", comment: "燃油种类")
        let energy = XTManageCenter.showPriceInComma(source: contentModel?.energy ?? "")
        engineModel.value = energy
        self.dataArray.insert(engineModel, at: 0)
        
        //座位数
        let energyModel = EntitiesModel.init()
        energyModel.paramName = MMLocalizedString("seat_num", comment: "座位数")
        if self.seaCarFlag {
            //海外车辆详情取seatNum
            energyModel.value = "\(contentModel?.seatNum ?? 0)"
        }else{
            energyModel.value = "\(contentModel?.seatCount ?? 0)"
        }
        self.dataArray.insert(energyModel, at: 1)
        
        
        if !self.seaCarFlag {
            //本地车，计算高度
            self.dataArray.forEach { item in
                let tempStr = (item.paramName ?? "") + ": " + (item.value ?? "")
                let tempHeight = XTManageCenter.getLabHeight(labelStr: tempStr, font: UIFont.init(name: Theme.PingFangSCRegular, size: 14)!, width: kScreenWidth / 2)
                item.paramNameHeight = tempHeight
            }
        }
        
        
        
        self.collectionView.reloadData()
        self.collectionView.layoutIfNeeded()
        let tempH = self.collectionView.collectionViewLayout.collectionViewContentSize.height
        self.collectionView.snp.updateConstraints { make in
            make.height.greaterThanOrEqualTo(tempH)
        }
        self.updateConstraints()
        self.layoutIfNeeded()
        
//        if let table = self.superview as? UITableView {
//            table.beginUpdates()
//            table.endUpdates()
//        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
}

extension SpecificationTableViewCell: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SpecificationCell", for: indexPath) as! SpecificationCell
        cell.seaCarFalg = self.seaCarFlag
        if self.dataArray.count > indexPath.row {
            let infoModel = self.dataArray[indexPath.row]
            cell.setModel(model: infoModel)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        var titleHeight: CGFloat = 35
        if self.dataArray.count > indexPath.row {
            let infoModel = self.dataArray[indexPath.row]
            let tempStr = (infoModel.paramName ?? "") + ": " + (infoModel.value ?? "")
            let aHeight = XTManageCenter.getLabHeight(labelStr: tempStr, font: UIFont.init(name: Theme.PingFangSCRegular, size: 14)!, width: self.seaCarFlag ? (kScreenWidth - 30): (kScreenWidth/2 - 40))
            titleHeight = max(infoModel.valueHeight, infoModel.paramNameHeight, 45, aHeight + 10)
        }
        
        //海外车只展示一列
        //本地车展示两列
        if self.seaCarFlag {
            return CGSize(width: kScreenWidth, height: titleHeight)
        }else{
            return CGSize(width: kScreenWidth / 2, height: titleHeight)
        }
    }
}
